//
//  VideoPublishProgressView.swift
//  TestDemo
//
//  Created by ayin on 2019/2/20.
//  Copyright © 2019 aYin. All rights reserved.
//

import UIKit
import SnapKit

enum VideoPublishResultState {
    case success
    case error
    case close
}

enum VideoPublishErrorType {
    case compress
    case uploadQN
    case publishRequest
}

protocol VideoPublishProgressViewDelegate : NSObjectProtocol {
    
}

class VideoPublishProgressView: UIView {
    //MARK: - 声明属性
    lazy var topInfoView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        view.clipsToBounds = true
        return view
    }()
    
    lazy var avatorImgView:UIImageView = {
        let avatorImgView = UIImageView()
        avatorImgView.clipsToBounds = true
        avatorImgView.isUserInteractionEnabled = true
        avatorImgView.contentMode = .scaleAspectFit
        avatorImgView.backgroundColor = UIColor.red
        return avatorImgView
    }()
    
    lazy var progressLB:UILabel = {
        let progressLB = UILabel.makeLabel(font: UIFont.systemFont(ofSize: 14), text: "视频上传中(0%)", textColor: UIColor.black, numberLine: 1, alignment: .left)
        return progressLB
    }()
    
    lazy var retryBtn:UIButton = {
        let retryBtn = UIButton.makeButton(font: UIFont.systemFont(ofSize: 14), title: "点击重试", titleColor: UIColor.blue, image: nil, bgColor: UIColor.clear)
        retryBtn.addTarget(self, action: #selector(retryBtnAction), for: .touchUpInside)
        return retryBtn
    }()
    
    lazy var closeBtn:UIButton = {
        let closeBtn = UIButton.makeButton(font: nil, title: nil, image: "iconClose")
        closeBtn.addTarget(self, action: #selector(closeBtnAction), for: .touchUpInside)
        return closeBtn
    }()
    
    lazy var progress:UIProgressView = {
        let progress:UIProgressView = UIProgressView(progressViewStyle: .default)
        progress.trackTintColor = UIColor.white
        progress.progressImage = UIImage(named: "icon_button")
        progress.layer.masksToBounds = true
        return progress
    }()
    
    var videoUrl:URL?//暂时，需替换为model
    var errorType:VideoPublishErrorType?
    var publishResultBlock:((_ state: VideoPublishResultState, _ model: Any?) -> Void)?
    
    //MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    //MARK: - 搭建UI
    fileprivate func setupUI() {
        addSubview(topInfoView)
        topInfoView.addSubview(avatorImgView)
        topInfoView.addSubview(progressLB)
        topInfoView.addSubview(retryBtn)
        topInfoView.addSubview(closeBtn)
        addSubview(progress)
        
        topInfoView.snp.makeConstraints { (make) in
            make.top.left.width.equalToSuperview()
            make.height.equalTo(50)
        }
        
        avatorImgView.snp.makeConstraints { (make) in
            make.width.height.equalTo(36)
            make.left.equalTo(12)
            make.centerY.equalToSuperview()
        }
        avatorImgView.layer.cornerRadius = 18
        
        progressLB.snp.makeConstraints { (make) in
            make.left.equalTo(avatorImgView.snp.right).offset(12)
            make.centerY.equalToSuperview()
            make.right.lessThanOrEqualToSuperview().offset(-150)
        }
        
        retryBtn.snp.makeConstraints { (make) in
            make.left.equalTo(progressLB.snp.right).offset(10)
            make.width.equalTo(80)
            make.height.centerY.equalToSuperview()
        }
        
        closeBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(12)
            make.right.equalToSuperview().offset(-12)
            make.centerY.equalToSuperview()
        }
        
        progress.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(3)
            make.top.equalTo(topInfoView.snp.bottom)
        }
    }
    
    //MARK: - 刷新
    func resetUI() {
        self.topInfoView.isHidden = false
        self.retryBtn.isHidden = true
        self.closeBtn.isHidden = true
        self.topInfoView.snp.updateConstraints { (make) in
            make.height.equalTo(50)
        }
        
        self.progress.progress = 0
        self.progressLB.text = "视频上传中(0%)"
    }
    
    func refreshUIWithUploading(_ progressValue: Float,_ animated: Bool) {
        self.topInfoView.isHidden = false
        self.retryBtn.isHidden = true
        self.closeBtn.isHidden = true
        self.topInfoView.snp.updateConstraints { (make) in
            make.height.equalTo(50)
        }
        
        progress.setProgress(progressValue, animated: animated)
        
        let percentProgress:Int = Int(progressValue * 100)
        progressLB.text = "视频上传中(\(percentProgress)%)"
    }
    
    func refreshUIWithSlide() {
        self.topInfoView.isHidden = true
        self.topInfoView.snp.updateConstraints { (make) in
            make.height.equalTo(0)
        }
    }
    
    func refreshUIWithError() {
        self.topInfoView.isHidden = false
        self.retryBtn.isHidden = false
        self.closeBtn.isHidden = false
        self.topInfoView.snp.updateConstraints { (make) in
            make.height.equalTo(50)
        }
    }
}

extension VideoPublishProgressView {
    //MARK: - 事件
    //MARK: 按钮事件
    @objc func retryBtnAction() {
        guard let type = self.errorType else {
            return
        }
        switch type {
        case .compress:
            self.resetUI()
            self.step1CompressVideo(self.videoUrl!, nil)
        case .uploadQN:
            if self.progress.progress > 0.5 {
                self.progress.progress = 0.5
                progressLB.text = "视频上传中50%"
            }
            self.step2VideoUploadQN(self.videoUrl!, nil)
        case .publishRequest:
            if self.progress.progress > 0.95 {
                self.progress.progress = 0.95
                progressLB.text = "视频上传中95%"
            }
            self.step3VideoPublishRequest(self.videoUrl!, nil)
        }
    }
    
    @objc func closeBtnAction() {
        self.deleteFile(path: "")
        if self.publishResultBlock != nil {
            self.publishResultBlock!(.close,nil)
        }
    }
    
    //MARK: 上传事件
    func startUploadVideo(_ videoUrl:URL,_ completionHandler: @escaping ((_ state: VideoPublishResultState, _ model: Any?) -> Void)) {
        self.videoUrl = videoUrl
        self.publishResultBlock = completionHandler
        self.resetUI()
//        self.step1CompressVideo(videoUrl, nil)
        self.step2VideoUploadQN(videoUrl, nil)
        
//        let semaphore = DispatchSemaphore(value: 0)
//        DispatchQueue.global().async { [weak self] in
//            guard let weakSelf = self else {return}
//            weakSelf.step1CompressVideo(videoUrl, semaphore)
//            weakSelf.step2VideoUploadQN(videoUrl, semaphore)
//            weakSelf.step3VideoPublishRequest(videoUrl, semaphore)
//        }
    }
    
    //Step1:压缩
    func step1CompressVideo(_ videoUrl:URL,_ semaphore:DispatchSemaphore?) {
        let outputFileUrl = URL(fileURLWithPath: self.setupOutputFilePath())
        CompressVideoManager.shared.customCompressVideo(videoUrl, outputVideoUrl: outputFileUrl, { (progress) in
            DispatchQueue.main.async {
                self.refreshUIWithUploading(progress, true)
            }
        }, { (state, url) in
            if state == .success {
                self.step2VideoUploadQN(url!, nil)
//                semaphore.signal()
            }else {
                DispatchQueue.main.async {
                    self.refreshUIWithError()
                }
                self.errorType = .compress
                if self.publishResultBlock != nil {
                    self.publishResultBlock!(.error,nil)
                }
            }
        })
//        semaphore.wait()
    }
    
    //Step2:上传七牛
    func step2VideoUploadQN(_ videoUrl:URL,_ semaphore:DispatchSemaphore?) {
        QNContentUploadManager.share.uploadVideo(filePath: videoUrl.relativePath, progressBlock: { (progress) in
            DispatchQueue.main.async {
                self.refreshUIWithUploading(progress, true)
            }
        }) { (isSuccess, isTokenError, text) in
            if isSuccess {
                if self.publishResultBlock != nil {
                    self.publishResultBlock!(.success,nil)
                }
                return
                    
//                self.step3VideoPublishRequest(videoUrl, nil)
//                semaphore.signal()
            }else {
                DispatchQueue.main.async {
                    self.refreshUIWithError()
                }
                self.errorType = .uploadQN
                if self.publishResultBlock != nil {
                    self.publishResultBlock!(.error,nil)
                }
            }
        }
//        semaphore.wait()
    }
    
    //Step3:上传自身服务器，发布视频
    func step3VideoPublishRequest(_ videoUrl:URL,_ semaphore:DispatchSemaphore?) {
        //数据请求
        let requestState:Bool = false
        if requestState {
            self.deleteFile(path: "ddddd")
            if self.publishResultBlock != nil {
                self.publishResultBlock!(.success,nil)
            }
        }else {
            DispatchQueue.main.async {
                self.refreshUIWithError()
            }
            self.errorType = .publishRequest
            if self.publishResultBlock != nil {
                self.publishResultBlock!(.error,nil)
            }
        }
    }
    
    
    //MARK: 其他事件
    // 设置视频压缩后保存地址
    func setupOutputFilePath()->String {
        //暂时用时间戳，需替换为视频名字
        let now = Date()
        let timeInterval:TimeInterval = now.timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        let name = String(timeStamp) + ".mp4"
        let temporaryFilePath = NSTemporaryDirectory() + name
        return temporaryFilePath
    }
    
    //Step4:删除本地文件
    func deleteFile(path:String) {
        if FileManager.default.fileExists(atPath: path) {
            try? FileManager.default.removeItem(atPath: path)
        }
    }
}

